package s

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
)

func (self Str) ParseFileContent() Str {
	n := self.Copy()
	for _, name := range FileRe.FindAllString(self.String(), -1) {
		if f, err := os.Stat(name[1:]); err == nil && !f.IsDir() {
			buf, err := ioutil.ReadFile(name[1:])
			if err == nil {
				n = n.Replace(name, string(buf))
			}
		}
	}
	return n
}

func (self Str) FileExists() bool {
	if f, err := os.Stat(self.String()); err == nil && !f.IsDir() {
		return true
	}
	return false
}

func (self Str) IsFile() bool {
	if f, err := os.Stat(self.String()); err == nil && !f.IsDir() {
		return true
	}
	return false
}

func (self Str) IsDir() bool {
	if f, err := os.Stat(self.String()); err == nil && f.IsDir() {
		return true
	}
	return false
}

func (self Str) FilePathJoin(otherPaths ...any) Str {
	out := self.Copy()
	if otherPaths != nil {
		for _, otherPath := range otherPaths {
			if fp, ok := otherPath.(Str); ok {
				if fp.Has("~") {
					outstr, _ := os.UserHomeDir()
					fp = fp.Replace("~", outstr)
				}
				out = Str(filepath.Join(self.String(), fp.String()))

			} else if fp, ok := otherPath.(string); ok {
				if Str(fp).Has("~") {
					outstr, _ := os.UserHomeDir()
					fp = Str(fp).Replace("~", outstr).String()
				}
				out = Str(filepath.Join(self.String(), fp))
			} else {
				SafePush(&ErrStack, fmt.Errorf("%s", "not str /string arg"))
				return ""
			}

		}

	}
	return out
}

func (self Str) FileList() List[Str] {
	fs, err := ioutil.ReadDir(self.String())
	if err != nil {
		SafePush(&ErrStack, err)
		return List[Str]{}
	}
	e := List[Str]{}
	for _, f := range fs {
		e = append(e, self.FilePathJoin(Str(f.Name())))
	}
	return e
}
